<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(100000, 999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }

}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_1');
    $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . $key . '&address=' . urlencode($address);
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == '1') {
        $jsonResponse['geocodes'][0]['location'] = explode(',', $jsonResponse['geocodes'][0]['location']);
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['geocodes'][0]['location']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

function objectToArray($object)
{
    $jsonString = json_encode($object);
    $array = json_decode($jsonString, true);

    return $array;
}
//生成小程序二维码
function qrcode($name, $value = 123, $page , $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($name . '=' . $value, [
            'page' => $page,
            'width' => $width,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time() . $business_id);
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }
        msg(-1,'',$response);
        return -1;
    } catch (\Exception $e) {
        msg(-1,$e->getMessage(),'');
        return -1;
    }
}




